// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import FileModule from "../../module/FileModule";

const {ccclass, property} = cc._decorator;

const ColorConfigPath = "color_config";
const defaultColor = cc.color(180, 180, 180);

@ccclass
export default class ColorConfig{

    public static _instance: ColorConfig = null;

    private _colorMap: Object = {};

    static getModule(): ColorConfig {
        if (ColorConfig._instance == null) {
            ColorConfig._instance = new ColorConfig();
        }
        return ColorConfig._instance;
    }

    setConfigItem (key: string, value: cc.Color) {
        this._colorMap[key] = {r: value.r, g: value.g, b: value.b};
        this.save();
    }

    getColor (key) {
        let value = this._colorMap[key];
        if (value == null) {
            return defaultColor;
        }
        return cc.color(value.r, value.g, value.b);
    }

    publish () {
        cc.director.emit('SetGatherColor', this._colorMap);
    }

    save () {
        FileModule.saveJson(ColorConfigPath, this._colorMap);
    }

    async load () {
        let colorMap = await FileModule.loadJsonAsync(ColorConfigPath);
        if (colorMap) {
            this._colorMap = colorMap;
            cc.director.emit('SetGatherColor', this._colorMap);
        }
    }
}
